package afcp.alumni.dao.base;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import afcp.alumni.model.SearchResult;
import afcp.alumni.model.base.SAPIEntity;

public abstract class DaoDatastoreIndexable<T extends SAPIEntity> extends
		DaoDatastore<T> {
	
	protected DaoSearchAPI sapi = DaoSearchAPI.getInstance();
	
	public SearchResult<T> search(String queryString, int page, int perPage, Locale locale) {
		int firstElementIncluded = (page-1)*perPage;
		int lastElementExcluded = page*perPage;
		List<String> foundEntityIds = sapi.search(queryString, this.getClassObject().getSimpleName());
		List<String> returnedEntityIds = new LinkedList<>();
		int size = foundEntityIds.size();
		if (size > firstElementIncluded) {
			for (int i=firstElementIncluded; i<lastElementExcluded && i<size; i++) {
				returnedEntityIds.add(foundEntityIds.get(i));
			}
		}
		return this.findFromKeyStrings(returnedEntityIds, page, perPage, locale);
	}

	@Override
	public boolean addOrUpdate(T entity) {
		// Search API part && Datastore part
		return super.addOrUpdate(entity) & sapi.add(entity);
	}

	@Override
	public boolean addOrUpdate(List<T> entities) {
		return super.addOrUpdate(entities) & sapi.add(entities);
	}

	@Override
	public T removeFromKeyString(String id) {
		sapi.remove(id, className);
		return super.removeFromKeyString(id);
	}

	@Override
	public boolean remove(List<String> ids) {
		return super.remove(ids) & sapi.remove(ids, className);
	}

	@Override
	public boolean update(T entity) {
		// TODO add sapi.update(entity) 
		return super.update(entity) & sapi.add(entity);
	}
	
	public boolean clearIndex() {
		return sapi.clearIndex();
	}
	
	public boolean addToIndex(List<T> entities) {
		return sapi.add(entities);
	}
}
